package org.csc.sss.admin.interceptor;

import org.csc.sss.datacore.annontation.WebLog;
import org.csc.sss.datacore.security.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.csc.sss.util.RequestUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class HandlerInterceptor extends HandlerInterceptorAdapter {

    /**
     * 获取当前登录的用户
     * @return
     */
    public SecurityUser getUser() {
        if (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof SecurityUser) {
            return (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        }
        return  null;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //方法请求之前拦截
        request.setAttribute("startTime", System.currentTimeMillis());
        HandlerMethod method = (HandlerMethod)handler;
        WebLog webLog = method.getMethod().getAnnotation(WebLog.class);
        String logger = "日志信息不存在";
        if (null != webLog) {
            logger = webLog.value();
        }
        log.info("URL = {}", request.getRequestURL().toString());
        log.info("CLASS_METHOD = {}, HTTP_METHOD = {},", method.getBean().getClass().getName() + "." + method.getMethod().getName(), request.getMethod());
        log.info("用户[{}],开始执行[{}]业务-请求参数:{}-requestBody:{}", null == this.getUser() ? "~public" : this.getUser().getId(), logger, RequestUtils.getParamMap(request), "");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //方法处理中拦截
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //方法处理完拦截
        HandlerMethod method = (HandlerMethod)handler;
        WebLog webLog = method.getMethod().getAnnotation(WebLog.class);
        String logger = "日志信息不存在";
        if (null != webLog) {
            logger = webLog.value();
        }
        long startTime = (long) request.getAttribute("startTime");
        long endTime = System.currentTimeMillis();
        log.info("用户[{}],执行[{}]业务完成-本次请求处理时间为: {}ms", null == this.getUser() ? "~public" : this.getUser().getId(), logger, new Long(endTime - startTime));
//        logger.info("返回的数据: {}", handler.);
        //持久化请求信息
        //TODO
    }
}
